package org.example.mallchat.common.event.listener;

import lombok.extern.slf4j.Slf4j;
import org.example.mallchat.common.event.UserOnlineEvent;
import org.example.mallchat.dao.UserDao;
import org.example.mallchat.domain.entity.User;
import org.example.mallchat.domain.enums.ChatActiveStatusEnum;
import org.example.mallchat.service.IpService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @author: zzh
 * @date: 2024/12/24 13:32:50
 * @version: 1.0
 */
// 事件监听器Spring容器的！
@Slf4j
@Component
public class UserOnlineListener {

    @Resource
    private UserDao userDao;


    @Resource
    private IpService ipService;

    // 监听UserOnlineEvent事件 入库用户信息(IP)
    @Async// 异步处理
    @TransactionalEventListener(classes = UserOnlineEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void onUserOnlineEventSaveDB(UserOnlineEvent event) {
        log.info("Received UserOnlineEvent: {}", event);
        // 处理用户上线事件
        User user = event.getUser();
        User update = new User();
        update.setId(user.getId());
        update.setLastOptTime(user.getLastOptTime());
        update.setIpInfo(user.getIpInfo());
        update.setActiveStatus(ChatActiveStatusEnum.ONLINE.getStatus());// 状态改为在线
        userDao.updateById(update);
        //更新用户ip详情
        ipService.refreshIpDetailAsync(user.getId());
    }
}
